package com.penghaisoft.microwms.material.web.intowarehouse.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.base.model.BaseDictionary;
import com.penghaisoft.microwms.common.controller.BaseController;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.dto.TransResult;
import com.penghaisoft.microwms.common.page.Pager;
import com.penghaisoft.microwms.common.service.IWmsCommonService;
import com.penghaisoft.microwms.common.util.ExcelExpUtil;
import com.penghaisoft.microwms.common.wms.model.RawAuditingHis;
import com.penghaisoft.microwms.common.wms.model.RawBarcode;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.material.web.insidewarehouse.service.IBaseDictionaryService;
import com.penghaisoft.microwms.material.web.intowarehouse.service.IMaterialIntoService;

/**
 * @Description 原材料条码入库
 * @author luoteng
 * @date 2018年5月23日 下午5:26:31
 * @version 1.0
 */
@RestController
@RequestMapping(value = "intowarehouse")
@Slf4j
public class MaterialIntoController extends BaseController {

	@Autowired
	private IMaterialIntoService materialIntoService;

	@Autowired
	private IWmsCommonService wmsCommonService;
	
	@Autowired
	private IBaseDictionaryService baseDictionaryService;

	/**
	 * @Title list
	 * @Description 原材料条码查询列表
	 * @author luoteng
	 * @date 2018年5月23日:下午2:22:46
	 * @param page
	 * @param rows
	 * @param rawBarcode
	 * @return TransResult
	 */
	@PostMapping("barcode/list")
	public TransResult listBarcode(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			RawBarcode rawBarcode) {
		rawBarcode.setActiveFlag("1");
		Pager<RawBarcode> result = materialIntoService.findListByCondition(
				page, rows, rawBarcode);
		
		return success(result);
	}

	/**
	 * @Title edit
	 * @Description 条码修改、新增
	 * @author luoteng
	 * @date 2018年5月23日:下午5:32:16
	 * @param rawBarcode
	 * @return TransResult
	 */
	@PostMapping("barcode/edit")
	public TransResult editBarcode(RawBarcode rawBarcode) {
		TransResult result = new TransResult();
		Date now = new Date();
		if(rawBarcode.getModelType() != null){
			if(rawBarcode.getModelType().equals(Constant.MODEL_WT)
					|| rawBarcode.getModelType().equals(Constant.MODEL_ST) 
					|| rawBarcode.getModelType().equals(Constant.MODEL_BJ)
					|| rawBarcode.getModelType().equals(Constant.MODEL_GD)){
				if(rawBarcode.getAmount() == null){
					result.setCode(Constant.FAIL);
					result.setMsg("请输入计量值！");
					return result;
				}else if(rawBarcode.getAmount().compareTo(new BigDecimal(1)) != 0){
					result.setCode(Constant.FAIL);
					result.setMsg("管件的计量值只能为1！");
					return result;
				}
			}else if(rawBarcode.getModelType().equals(Constant.MODEL_B) || rawBarcode.getModelType().equals(Constant.MODEL_H)){
				result.setCode(Constant.FAIL);
				result.setMsg("黑白料不能生成条码！");
				return result;
			}
		}
		if (rawBarcode.getId() == null || "".equals(rawBarcode.getId())) {
			if (rawBarcode.getProductNum() != null
					&& Integer.parseInt(rawBarcode.getProductNum()) > 0) {
				List<String> barcodeList = wmsCommonService.getProBarCodeShortSeq5(rawBarcode.getModelType(), rawBarcode.getModelType(),
						Integer.parseInt(rawBarcode.getProductNum()));
				
				rawBarcode.setActiveFlag("1");
				// 状态 0：未打印 1：已打印
				rawBarcode.setStatus("0");
				// 入库状态：0 未入库 1已入库
				rawBarcode.setUserDefined1("0");
				rawBarcode.setCreateBy(getLoginName());
				rawBarcode.setGmtCreate(now);
//				materialIntoService.createBarcode(rawBarcode);
				materialIntoService.createBarcodeByList(rawBarcode, barcodeList);
			} else {
				result.setCode(Constant.FAIL);
				result.setMsg("请输入生成条码个数！");
				return result;
			}
		} else {
			rawBarcode.setLastModifiedBy(getLoginName());
			rawBarcode.setGmtModified(now);
			materialIntoService.updateBarcodeRelate(rawBarcode);
		}
		return success();
	}

	/**
	 * @Title get
	 * @Description 根据ID获取条码信息
	 * @author luoteng
	 * @date 2018年5月23日:下午5:55:34
	 * @param rawBarcode
	 * @return TransResult
	 */
	@GetMapping("barcode/get/{id}")
	public TransResult getBarcode(@PathVariable("id") String id) {
		RawBarcode rtnOb = new RawBarcode();
		if (id != null && !"".equals(id)) {
			RawBarcode ob = new RawBarcode();
			ob.setId(Integer.parseInt(id));
			List<RawBarcode> list = materialIntoService.getBarcodeList(ob);
			if (list != null && !list.isEmpty()) {
				rtnOb = list.get(0);
			}
		}
		return success(rtnOb);
	}

	/**
	 * @Title delBarcode
	 * @Description 删除条码
	 * @author luoteng
	 * @date 2018年5月24日:下午2:59:43
	 * @param ob
	 * @return TransResult
	 */
	@PostMapping("barcode/d")
	public TransResult delBarcode(RawBarcode ob) {
		Date now = new Date();
		// 有效标志 1-有效 0-无效
		ob.setActiveFlag("0");
		ob.setLastModifiedBy(getLoginName());
		ob.setGmtModified(now);
		materialIntoService.updateBarcodeRelate(ob);
		return success();
	}

	@PostMapping("barcode/intowh/list")
	public TransResult listBarcodeIntoWh(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			RawStorageSn rawStorageSn) {
		Pager<RawStorageSn> result = materialIntoService
				.findIntoWhRawStorageSnList(page, rows, rawStorageSn);
		
		String sumInfo = result.getOrder();
		if (sumInfo != null && sumInfo.length() > 0) {
			result.setOrder(sumInfo);
		}
		
		return success(result);
	}
	
	/** 
	* @Title: listIntoWhExp 
	* @Description: 原材料入库明细导出 
	* @param @param rawStorageSn
	* @param @param request
	* @param @param response
	* @param @return  参数说明 
	* @return String    返回类型
	* @author jzh 
	* @throws 
	*/
	@GetMapping("barcode/listIntoWhExp")
	public String listIntoWhExp(RawStorageSn rawStorageSn, HttpServletRequest request, HttpServletResponse response){
		
		List<RawStorageSn> dataList = materialIntoService.findIntoWhList(rawStorageSn);
		BaseDictionary baseDictionary1 = new BaseDictionary();
		baseDictionary1.setActiveFlag("1");
		baseDictionary1.setDicType("model_type");
		List<BaseDictionary> list1 = baseDictionaryService.queryAllByCondition(baseDictionary1);
		if (dataList != null && !dataList.isEmpty()) {
			for (RawStorageSn tmpData : dataList) {
				if (list1 != null && !list1.isEmpty()) {
					for (BaseDictionary tmp : list1) {
						// 判断产品类型
						if (tmp.getDicCode().equals(tmpData.getModelType())) {
							tmpData.setModelType(tmp.getDicName());
						}
		
						// 判断状态
						if ("0".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("可用");
						}
						else if ("1".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("冻结");
						}
						else if ("2".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("已出库");
						}
						else if ("3".equals(tmpData.getBarcodeStatus())) {
							tmpData.setBarcodeStatus("报废");
						}
						
					}
				}
			}
		}
		
		List<Map> columnList = new ArrayList<Map>();
		Map<String,String> columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "合同编号");
		columnMap.put("columnBeanName", "contractNo");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号代码");
		columnMap.put("columnBeanName", "model");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号描述");
		columnMap.put("columnBeanName", "modelDesc");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "型号类型");
		columnMap.put("columnBeanName", "modelType");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "条码");
		columnMap.put("columnBeanName", "barcode");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "单位");
		columnMap.put("columnBeanName", "unit");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "数量");
		columnMap.put("columnBeanName", "amount");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "状态");
		columnMap.put("columnBeanName", "barcodeStatus");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "创建时间");
		columnMap.put("columnBeanName", "gmtCreate");
		columnList.add(columnMap);
		columnMap = new HashMap<String,String>();
		columnMap.put("columnComment", "创建人");
		columnMap.put("columnBeanName", "createBy");
		columnList.add(columnMap);
		
		SXSSFWorkbook sw = ExcelExpUtil.generateWorkbook(dataList, columnList);
		
		OutputStream out = null;
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String sdfDate = sdf.format(date);
		String fileName = "原材料入库明细"+sdfDate+".xlsx";// 文件名
		try {
			out = response.getOutputStream();
			response.setContentType("application/force-download");// 设置强制下载不打开
			response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
			sw.write(out);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	return "sucess";
	}
	
	
	/**
	 * @param page
	 * @param rows
	 * @param rawBarcode
	 * @Description: 原材料审核列表
	 * @author Lengxf
	 * @return
	 */
	@PostMapping("barcode/auditing")
	public TransResult listAuditing(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			RawStorageSn rawStorageSn) {
		Pager<RawStorageSn> result = materialIntoService.findListAuditing(
				page, rows, rawStorageSn);
		
		return success(result);
	}
	
	
	/**
	 * @param rawStorageSn
	 * @return
	 * @author Lengxf
	 * @Descripting : 原材料退扫审核按钮
	 */
	@PostMapping("/auditing")
	public Resp audingting(RawStorageSn rawStorageSn){
		Resp resp = new Resp();
		 
		RawStorageSn entity = new RawStorageSn();
		entity.setStorageSnId(rawStorageSn.getStorageSnId());
		//取当前单条数据进行判断
		RawStorageSn tmp = materialIntoService.findByStroageSnId(entity);
		if("1".equals(tmp.getUserDefined4()) || "0".equals(tmp.getActiveFlag())){
			resp.setCode(Constant.FAIL);
			resp.setMsg("当前条码已通过审核或已完成退扫操作");
			return resp;
		}else {
			TransResult transResult = materialIntoService.delBarcode(rawStorageSn, getLoginName());
			resp.setCode(transResult.getCode());
			resp.setMsg(transResult.getMsg());
		}
		return resp;
	}
	
	/**
	 * @param page
	 * @param rows
	 * @param rawBarcode
	 * @Description: 原材料审核历史列表
	 * @author Lengxf
	 * @return
	 */
	@PostMapping("/auditing/his")
	public TransResult listAuditingHis(
			@RequestParam(name = "page", defaultValue = "1") int page,
			@RequestParam(name = "rows", defaultValue = "10") int rows,
			RawAuditingHis rawAuditingHis) {
		Pager<RawAuditingHis> result = materialIntoService.findListAuditingHis(
				page, rows, rawAuditingHis);
		
		return success(result);
	}
}
